import 'dart:math';

import 'package:flutter/material.dart';
import 'package:sensors/sensors.dart';
import 'dart:async';
import 'package:vibration/vibration.dart';

class ShakePage extends StatefulWidget {
  @override
  _ShakePageState createState() => _ShakePageState();
}

class _ShakePageState extends State<ShakePage> {
  bool isShake = false;
  int _currentIndex = 0;
  StreamSubscription _streamSubscription;
  static const int SHAKE_TIMEOUT = 500;
  static const double SHAKE_THRESHOLD = 3.25;
  var _lastTime = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _streamSubscription =
        accelerometerEvents.listen((AccelerometerEvent event) {
      // Do something with the event.
      var now = DateTime.now().millisecondsSinceEpoch;
      if ((now - _lastTime) > SHAKE_TIMEOUT) {
        var x = event.x;
        var y = event.y;
        var z = event.z;
        double acce = sqrt(x * x + y * y + z * z) - 9.8;//得到相对加速度  应该指的是地球引力常数g, 这个是根据地球质量以及距离以及万有引力公式计算出来的一个常数,在赤道附近的值约为9.8. 也就是说一个1kg重量的物体在地球...
        if(acce>SHAKE_THRESHOLD){
          //表示手机晃动
          _lastTime = now;
          if(!mounted)return;
          setState(() {
            isShake = true;
          });
//         if(Vibration != null){
           if(Vibration.hasVibrator() != null){
             Vibration.vibrate(duration: 500,amplitude: 128);
           }
//         }

        }
      }
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _streamSubscription.cancel();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('摇一摇'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Image.network(
              'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1571724546233&di=b24b59116f6e83f324c2e2f1b29cedd0&imgtype=0&src=http%3A%2F%2Fku.90sjimg.com%2Felement_origin_min_pic%2F17%2F01%2F14%2F9db74496f0dfbab9da1e5e72399dee72.jpg',
              width: 120.0,
              height: 120.0,
            ),
            SizedBox(
              height: 10.0,
            ),
            Text('摇一摇'),
          ],
        ),
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: [
          BottomNavigationBarItem(
            title: Text('礼品'),
            icon: Icon(Icons.print),
          ),
          BottomNavigationBarItem(
            title: Text('咨询'),
            icon: Icon(Icons.surround_sound),
          ),
        ],
        currentIndex: _currentIndex,
        onTap: (index) {
          if (mounted) {
            setState(() {
              _currentIndex = index;
              isShake = false;
            });
          }
        },
      ),
    );
  }
}
